import TagGroup from '@/components/TagGroup';
import { pageKeyword } from '@/services/api/api-datahub-keyword';
import { pageMark } from '@/services/api/api-datahub-mark';
import {
  getPretreatmentRecordAreaCascaders,
  putAssessPretreatmentRecord,
  selectPretreatmentRecord,
  updatePretreatmentRecord,
} from '@/services/api/api-datahub-record';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import {
  ActionType,
  DrawerForm,
  ProFormCascader,
  ProFormDatePicker,
  ProFormSelect,
  ProFormText,
  ProFormTextArea,
  ProTable,
} from '@ant-design/pro-components';
import { useAccess, useModel } from '@umijs/max';
import { Button, Cascader, Form, FormInstance, message, Modal, Spin, Tag, Typography } from 'antd';
import React, { useRef, useState } from 'react';
import AddKeyword from '../../keyword/components/AddKeyword';
import AddMark from '../../mark/components/AddMark';
interface ExamineRecordProps {
  data: DatahubRecordData.SelectRecord | undefined;
  onRefurbish: () => void;
}

const ExamineRecord: React.FC<ExamineRecordProps> = ({ data, onRefurbish }) => {
  const access = useAccess();
  const formRef = useRef<FormInstance>();
  const actionRef = useRef<ActionType>();
  const [areaList, setAreaList] = useState<DatahubRecordData.ChannelList[]>([]);
  const { initialState } = useModel('@@initialState');
  const { currentUser } = initialState || {};
  const [selectedKeywords, setSelectedKeywordsState] = useState<any[]>([]);
  const [selectedMarks, setSelectedMarksState] = useState<any[]>([]);

  const getDetail = async () => {
    const res = await selectPretreatmentRecord({ id: data?.id });

    console.log(res);
  };

  const getAreaList = async () => {
    const res = await getPretreatmentRecordAreaCascaders();
    if (res.code === 0) {
      setAreaList(res.data);

      const areas = data?.areas.filter((area) => {
        let isChongqing = false;

        area.forEach((item) => {
          if (item.id === '500000000000') {
            isChongqing = true;
          }
        });

        return !isChongqing;
      });


      console.log('========', areas);
      

      // formRef.current?.setFieldsValue({
      //   areaIds: [['500101000000']],
      // });

      formRef.current?.setFieldsValue({
        areaIds: areas?.map((item) => item.map((e) => e.id)),
      });

      console.log('===1==', res.data);

      console.log(
        '==2===',
        areas?.map((item) => item.map((e) => e.id)),
      );
    }
  };

  return (
    <DrawerForm
      title="审核"
      resize={{
        onResize() {
          console.log('resize!');
        },
        maxWidth: window.innerWidth * 0.8,
        minWidth: 400,
      }}
      formRef={formRef}
      trigger={<Button type="primary">审核</Button>}
      initialValues={{
        focusId: data?.focusId,
        dataName: data?.dataName,
        dataAbstracts: data?.dataAbstracts,
        dataContent: data?.dataContent,
        dataReleaseTime: data?.dataReleaseTime,
        sourceId: [data?.levelId, data?.sourceId],
        labelNames: data?.labels.map((item) => item?.name),
        keywords: data?.keywords?.map((item) => item?.name),
        marks: data?.marks?.map((item) => item?.name),
      }}
      autoFocusFirstInput
      drawerProps={{
        destroyOnClose: true,
        width: 1000,
      }}
      onOpenChange={(visible) => {
        if (visible) {
          getDetail();
          getAreaList();
          setSelectedKeywordsState(data?.keywords?.map((item) => item?.id));
          setSelectedMarksState(data?.marks?.map((item) => item?.id));
        } else {
          onRefurbish();
        }
      }}
      submitTimeout={2000}
      onFinish={async (values) => {
        const response = await updatePretreatmentRecord({
          ...values,
          keywordIds: selectedKeywords,
          markIds: selectedMarks,
          id: data?.id,
        });
        if (response.code === 0) {
          message.success('提交成功');

          Modal.confirm({
            title: '是否推送到文化报表服务中',
            icon: <ExclamationCircleOutlined />,
            okText: '是',
            cancelText: '否',
            async onOk() {
              try {
                const response = await putAssessPretreatmentRecord({ id: data?.id });
                if (response.code === 0) {
                  message.success('推送成功');
                }
              } catch (error) {
                message.success('推送失败');
              }
            },
          });

          onRefurbish();
          return true;
        } else {
          return false;
        }
      }}
    >
      <Spin spinning={areaList.length <= 0}>
        <ProFormSelect
          width="md"
          name="focusId"
          label="聚焦"
          request={async () => [
            { label: '头版头条', value: '7200000000100000' },
            { label: '整版', value: '7200000000200000' },
            { label: '单条', value: '7200000000300000' },
            { label: '综合报道', value: '7200000000400000' },
          ]}
          rules={[{ required: true, message: '请输入选择聚焦' }]}
        />

        <ProFormText
          name="dataName"
          label="标题"
          placeholder="请输入"
          rules={[{ required: true, message: '请输入标题' }]}
        />

        <ProFormCascader
          name="areaIds"
          placeholder="选择区域"
          label="区域"
          fieldProps={{
            options: areaList,
            multiple: true,
            removeIcon: true,
            allowClear: true,
            showSearch: true,
            maxTagCount: 'responsive',
            showCheckedStrategy: Cascader.SHOW_PARENT,
            displayRender: (labels: string[], selectedOptions?: any[]) => {
              const last = selectedOptions?.at(-1);

              return <span key={last?.value}>{last?.cascadersNames?.join('-')}</span>;
            },
          }}
        />
        <Form.Item
          label={
            <>
              <span
                style={{
                  color: '#ff4d4f',
                  fontSize: 14,
                  paddingRight: 4,
                }}
              >
                *
              </span>
              标签
            </>
          }
          name="labelNames"
          extra={'最少输入一个'}
        >
          <TagGroup />
        </Form.Item>
        <ProFormSelect
          name="keywords"
          label="关键词"
          showSearch
          fieldProps={{
            mode: 'multiple',
            allowClear: true,
            showSearch: true,
            showArrow: false,
            open: false,
            optionFilterProp: 'children',
            listHeight: 500,
            style: {
              width: 488,
            },
          }}
          addonAfter={
            <DrawerForm
              title="选择关键词"
              trigger={<a>点击添加</a>}
              submitter={false}
              autoFocusFirstInput
              drawerProps={{
                destroyOnClose: true,
                width: 600,
              }}
              submitTimeout={2000}
            >
              <ProTable<DatahubKeywordData.KeywordPage>
                columns={[
                  {
                    title: '名称',
                    key: 'name',
                    dataIndex: 'name',
                    width: '180px',
                    hideInSearch: true,
                  },

                  {
                    title: '类型',
                    key: 'types',
                    dataIndex: 'types',
                    valueType: 'select',
                    valueEnum: {
                      1: { text: '人名', status: 'Error' },
                      2: { text: '地域', status: 'Success' },
                      3: { text: '机构', status: 'Error' },
                      4: { text: '其他', status: 'Success' },
                    },
                    width: '100px',
                    render(dom, entity, index, action, schema) {
                      return entity.types.map((item) => (
                        <Tag
                          color={
                            item.id === '1'
                              ? '#f50'
                              : item.id === '2'
                              ? '#ffd591'
                              : item.id === '3'
                              ? 'orange'
                              : '#2db7f5'
                          }
                        >
                          {item.name}
                        </Tag>
                      ));
                    },
                  },
                ]}
                actionRef={actionRef}
                request={async (params = {}) => {
                  const response = await pageKeyword({
                    ...params,
                  });

                  return Promise.resolve({
                    data: response.data.data,
                    total: response.data.total,
                    success: response.code === 0,
                  });
                }}
                search={false}
                rowSelection={{
                  selectedRowKeys: selectedKeywords,
                  type: 'checkbox',
                  onChange: (selectedRowKeys: React.Key[], selectedRows: any) => {
                    const names = selectedRows.map((item: { name: any }) => item.name);
                    setSelectedKeywordsState(selectedRowKeys);
                    formRef.current?.setFieldsValue({
                      keywords: names,
                      keywordIds: selectedRowKeys,
                    });
                  },
                }}
                sticky
                rowKey="id"
                tableLayout="fixed"
                dateFormatter="string"
                bordered
                pagination={{
                  showQuickJumper: true,
                  showSizeChanger: true,
                  defaultPageSize: 20,
                }}
                options={{
                  search: {
                    name: 'name',
                    onSearch: (keyword: string) => {
                      setSelectedKeywordsState([]);
                      formRef.current?.setFieldsValue({
                        name: undefined,
                      });
                      return true;
                    },
                  },
                }}
                toolBarRender={() => [
                  access.数据仓x配置x管理员 && (
                    <AddKeyword
                      organization={{
                        key: currentUser?.organizationId,
                        title: currentUser?.organizationName,
                      }}
                      onRefurbish={() => {
                        actionRef.current?.reload();
                      }}
                    />
                  ),
                ]}
              />
            </DrawerForm>
          }
        />
        <ProFormSelect
          name="marks"
          label="标记"
          showSearch
          fieldProps={{
            mode: 'multiple',
            allowClear: true,
            showSearch: true,
            showArrow: false,
            open: false,
            optionFilterProp: 'children',
            listHeight: 500,
            style: {
              width: 488,
            },
          }}
          addonAfter={
            <DrawerForm
              title="选择标记"
              trigger={<a>点击添加</a>}
              submitter={false}
              autoFocusFirstInput
              drawerProps={{
                destroyOnClose: true,
                width: 600,
              }}
              submitTimeout={2000}
            >
              <ProTable<DatahubMarkData.MarkPage>
                columns={[
                  {
                    title: '名称',
                    key: 'name',
                    dataIndex: 'name',
                    width: '180px',
                    hideInSearch: true,
                  },
                  {
                    title: '描述',
                    key: 'describes',
                    dataIndex: 'describes',
                    render(dom, entity, index, action, schema) {
                      return (
                        <Typography>
                          <Typography.Paragraph>{entity.describes}</Typography.Paragraph>
                        </Typography>
                      );
                    },
                  },
                ]}
                actionRef={actionRef}
                request={async (params = {}) => {
                  const response = await pageMark({
                    ...params,
                  });

                  return Promise.resolve({
                    data: response.data.data,
                    total: response.data.total,
                    success: response.code === 0,
                  });
                }}
                search={false}
                rowSelection={{
                  selectedRowKeys: selectedMarks,
                  type: 'checkbox',
                  onChange: (selectedRowKeys: React.Key[], selectedRows: any) => {
                    const names = selectedRows.map((item: { name: any }) => item.name);
                    setSelectedMarksState(selectedRowKeys);
                    formRef.current?.setFieldsValue({
                      marks: names,
                      markIds: selectedRowKeys,
                    });
                  },
                }}
                sticky
                rowKey="id"
                tableLayout="fixed"
                dateFormatter="string"
                bordered
                pagination={{
                  showQuickJumper: true,
                  showSizeChanger: true,
                  defaultPageSize: 20,
                }}
                options={{
                  search: {
                    name: 'name',
                    onSearch: (keyword: string) => {
                      setSelectedMarksState([]);
                      return true;
                    },
                  },
                }}
                toolBarRender={() => [
                  access.数据仓x配置x管理员 && (
                    <AddMark
                      onRefurbish={() => {
                        actionRef.current?.reload();
                      }}
                    />
                  ),
                ]}
              />
            </DrawerForm>
          }
        />
        <ProFormDatePicker
          name="dataReleaseTime"
          width="lg"
          rules={[{ required: true, message: '请选择发布时间' }]}
          label="发布时间"
        />
        <ProFormTextArea
          name="dataAbstracts"
          label="摘要"
          placeholder="请输入"
          fieldProps={{
            allowClear: true,
            rows: 3,
            maxLength: 5000,
          }}
        />
        <ProFormTextArea
          name="dataContent"
          label="内容"
          placeholder="请输入"
          rules={[{ required: true, message: '请输入文章内容' }]}
          fieldProps={{
            allowClear: true,
            rows: 50,
            maxLength: 100000,
          }}
        />
      </Spin>
    </DrawerForm>
  );
};
export default ExamineRecord;
